<template>
    <span>
<!--        <template v-if="formData!=undefined&&propName!=undefined">-->
        <!--            {{formData[propName]}}-->
        <!--        </template>-->
        <!--        {{lookupDomainTable.list}}-->
        <!--        <template v-if="sksReadonly">-->
        <!--            <template v-for="(item,index) in currentList">-->
        <!--                <template v-for="tmp in lookupDomainTable.list">-->
        <!--                    <template v-if="item==tmp[optionKey]">-->
        <!--                        <template v-if="$slots.optionLabel">-->
        <!--                            <slot name="optionLabel" :item="tmp"></slot>-->
        <!--                        </template>-->
        <!--                        <template v-else>-->
        <!--                            {{defaultFormatLabel(item)}}-->
        <!--                        </template>-->
        <!--                    </template>-->
        <!--                </template>-->
        <!--            </template>-->
        <!--        </template>-->
        <!--        <template v-else>-->
            <el-select v-model="currentList" :placeholder="placeholder"
                       :disabled="disabled||sksReadonly"
                       :filterable="filterable"
                       :multiple="true"
                       :clearable="clearable"
                       @change="handleChangeValue"
                       :style="styles"
                       @visible-change="handleVisibleChange"
            >
              <template slot="prefix" v-if="$slots.prefix">
                <slot name="prefix"></slot>
              </template>
                <el-option
                    v-for="item in lookupDomainTable.list"
                    :key="item[optionKey]"
                    :value="item[optionKey]"
                    :label="defaultFormatLabel(item)"
                    :disabled="sksReadonly||optionDisabledFunc(item)"
                    class="item-option"
                >
                    <!--只会搜索 :label 中的内容-->
                    <template>
                        <slot name="optionLabel" :item="item"></slot>
                    </template>
                </el-option>
            </el-select>
        <!--        </template>-->
    </span>
</template>

<script>
//用于业务选择
import {Message} from "element-ui";
import {
    deepCopy,
    equalsObjectJson,
    findRowInListFromAttrName, isNullOrUndefined, mergeFromObject,
    resetSksTableBefore,
    safeGet,
    strIsEmpty
} from "../../../core";
import {newSksTable} from "../../../sks-model-utils";

export default {
    name: "SksSelectMultipleByLookupController",
    props:{
        /**
         * true: 显示为只读组建
         ***/
        sksReadonly:{
            type: Boolean,
            default: false
        },
        //form表单数据
        formData:[Object],
        //属性名
        propName:[String],
        //用于清空校验
        //已撤销,初始化时绑定会无效,可能渲染完之后 $refs才生效
        formRef: Object,
        //禁用选项方法,true: 禁用选项
        optionDisabledFunc: {
            type: Function,
            default: (item)=>{
                return false
            }
        },
        //值类型,number/string
        //会将 optionKey对应的值 转换为 number/string
        //转换逻辑还未写
        valueType: {
            type: String,
            default: 'number',
        },
        //点击下拉框时重新查找数据
        visibleChangeLookup:{
            type:Boolean,
            default:true,
        },
        //值类型为字符串,逗号分割
        value:[String],
        //如果该行信息下拉选项中不存在,将会插入到list最后一行,因为第一行可能会有标题,所以添加到最后
        //避免下拉数据被过滤掉了不显示
        valueRowList: [Array],
        disabled:[Boolean],
        clearable: Boolean,
        filterable:{
            type:Boolean,
            default:true,
        },
        placeholder:{
            type: String,
            default: '请选择或搜索'
        },
        //宽度对于 1000px 无效
        //        100%   有效
        width:[String],
        buttonText:[String],
        /**
         * 集合存放key的字段名
         * 例如: userId   depId
         ***/
        optionKey:[String],
        optionLabel:[String],
        //显示选中后的信息,搜索也会根据该信息
        formatOptionLabel:[Function],

        //如果对应选择列不存在,添加到顶部位置的数组,
        //数据类型需要保持与字段类型一致
        unshiftOptionList: Array,

        //分隔符
        separator:{
            type: String,
            default: ',',
        },
        requestUrl: [String],
        queryParams: Object,
        //true: 禁用查询,某些条件不满足时,不进行查询
        queryDisable: Boolean,
        /**
         * 限制查询频率,单位毫秒
         * 用于解决查询属性中使用会出现多次请求的情况
         ***/
        limitQueryRate:{
            type: Number,
            default: 2*1000
        },
    },
    computed: {
        styles(){
            let style = {};
            if (this.width) {
                style.width = `${this.width}`;
            }else{
                style.width = `100%`;
            }
            return style;
        },
    },
    watch:{
        requestUrl:{
            handler(val){
                this.lookupList()
            },
            immediate: true,
            deep: true,
        },
        queryParams:{
            handler(val){
                if (!equalsObjectJson(this.queryParamsCache,this.queryParams)) {
                    this.queryParamsCache=this.queryParams
                    console.log("watch.queryParams,this.queryParamsCache,this.queryParams",this.queryParamsCache,this.queryParams)
                    this.lookupList()
                }
            },
            immediate: true,
            deep: true,
        },
        valueRowList:{
            handler(val){
                this.mergeValueRowToList()
            },
            immediate: true,
        },
        // value: {
        //     handler(val) {
        //         if (val != this.currentValue) {
        //             this.currentValue=val;
        //             this.stringConvertToCurrentList()
        //         }
        //     },
        //     immediate: true,
        // },
        formData:{
            handler(val){
                if(isNullOrUndefined(this.formData)){
                    this.currentValue=undefined
                    this.stringConvertToCurrentList()
                    return
                }
                if(isNullOrUndefined(this.propName)) {
                    this.currentValue=undefined
                    this.stringConvertToCurrentList()
                    return
                }
                if(safeGet(this.formData,this.propName)!=this.currentValue){
                    this.currentValue=this.formData[this.propName]
                    this.stringConvertToCurrentList()
                }
            },
            immediate: true,
            deep: true,
        },

    },
    data(){
        return {
            lookupDomainTable: newSksTable(),
            //
            currentValue: undefined,
            //当前数组
            currentList: [],

            //查询缓存
            queryParamsCache: undefined,
        }
    },
    mounted() {
        //console.log("sksSelect mounted")
        // if(!this.lookupDomainTable.loading){
        //     this.lookupList()
        // }
        // this.lookupList()
    },
    methods:{
        handleVisibleChange(e){
            if(e&&this.visibleChangeLookup){
                this.lookupList();
            }
            // console.log("sksSelect handleVisibleChange",e)
        },
        lookupList(lookupSearchValueListCustomize,queryDisable=this.queryDisable){
            if(this.queryDisable){
                return
            }
            if(strIsEmpty(this.requestUrl)){
                Message.error("requestUrl不能为空")
                return
            }
            //毫秒
            let time = new Date().getTime()
            if (isNullOrUndefined(this.lastLookupTime)) {
                this.lastLookupTime=time
            }else{
                if ((this.lastLookupTime + this.limitQueryRate) > time) {
                    //组多2秒查询一次
                    return
                }
                this.lastLookupTime=time
            }
            resetSksTableBefore(this.lookupDomainTable)
            let queryParams=mergeFromObject({},this.queryParams,{
                // pageNum: this.selectTable.queryParams.pageNum,
                // pageSize: this.selectTable.queryParams.pageSize,
                pageNum: 1,
                //这里暂不考虑使用远程搜索每页限制,因为远程搜索时还要考虑原记录ID在当前页不存在时的情况
                pageSize: this.remote?50:0xffff,
            })
            if(isNullOrUndefined(queryParams.sksParams)){
                queryParams.sksParams={}
            }
            queryParams.sksParams.lookupSearchValueListCustomize= lookupSearchValueListCustomize
            this.$SKS_PLUGIN_EL_ERP.request({
                url: this.requestUrl,
                headers: {
                    repeatSubmit: false,
                },
                method: 'post',
                data: queryParams
            }).then(saRes=>{
                //console.log("saRes",saRes)
                let list = saRes.data.list;
                //console.log("saRes",saRes.data)
                for (let item of list) {
                    if(this.valueType==='string'){
                        //所有选择的值转换为字符串
                        item[this.optionKey]=''+item[this.optionKey]
                    }else{
                        //所有选择的值转换为字符串
                        item[this.optionKey]=item[this.optionKey]
                    }
                }
                this.lookupDomainTable.list=list
                this.lookupDomainTable.total=list.length
                if(strIsEmpty(lookupSearchValueListCustomize)){
                    if(this.unshiftOptionList){
                        for (let unshiftOption of this.unshiftOptionList) {
                            if(isNullOrUndefined(unshiftOption)){
                                continue
                            }
                            let optionKeyZeroValue=unshiftOption[this.optionKey]
                            let tmp = findRowInListFromAttrName(list,this.optionKey,optionKeyZeroValue,true)
                            if(tmp==undefined){
                                list.unshift(unshiftOption)
                            }
                        }
                    }

                    this.mergeValueRowToList(list)
                }
            }).catch(e=>{

            })
        },
        mergeValueRowToList(list = this.lookupDomainTable.list) {
            //console.log("mergeValueRowToList.list=",list,",valueRow",this.valueRowList,",optionKey=",this.optionKey)
            if (!isNullOrUndefined(this.valueRowList) ) {
                for(let valueRow of this.valueRowList){
                    if(isNullOrUndefined(valueRow)||strIsEmpty(this.optionKey)){
                        continue
                    }
                    if (!isNullOrUndefined(valueRow[this.optionKey])) {
                        let row = findRowInListFromAttrName(list, this.optionKey, valueRow[this.optionKey]);
                        // console.log("mergeValueRowToList.findRowInListFromAttrName=",row)
                        if (isNullOrUndefined(row)) {
                            let item=deepCopy(valueRow)
                            //console.log("mergeValueRowToList.valueRow-item=",item)
                            if (this.valueType === 'string') {
                                //所有选择的值转换为字符串
                                item[this.optionKey] = '' + item[this.optionKey]
                            }
                            list.push(item)
                        }
                    }
                }
            }
        },
        defaultFormatLabel(item){
            if(isNullOrUndefined(this.formatOptionLabel)){
                return this.optionLabel===undefined?item[this.optionKey]:item[this.optionLabel]
            }
            return this.formatOptionLabel(item)
        },
        stringConvertToCurrentList(){
            if (strIsEmpty(this.currentValue)) {
                this.currentList=[]
                if(this.currentValue!=''){
                    //如果不为空字符，则设置为空字符
                    this.updateValue('')
                }
                return
            }
            this.currentList=[]
            //是否存在重复值
            let hasDuplicateValue=this.appendValueToCurrentList(this.currentValue)
            if(hasDuplicateValue){
                const newVal=this.convertListToValue()
                this.updateValue(newVal)
            }
        },
        appendValueToCurrentList(appendValue=''){
            if(strIsEmpty(appendValue)){
                return false
            }
            let tmp=this.currentList
            //中文逗号转换为英文逗号
            let valTmp=typeof(appendValue) ==='string'?appendValue.replaceAll("，",","):appendValue+''
            //是否存在重复值
            let hasDuplicateValue=false
            for (let val of valTmp.split(this.separator)) {
                if(strIsEmpty(val)){
                    continue
                }
                if (tmp.some(o => o === val)) {
                    //已存在元素
                    hasDuplicateValue=true
                    continue
                }
                tmp.push(val)
            }
            return hasDuplicateValue;

        },
        convertListToValue(){
            let valTmp=[]
            for (let item of this.currentList) {
                if(strIsEmpty(item)){
                    continue
                }
                valTmp.push(item)
            }
            valTmp=[...new Set(valTmp)]
            const newVal=valTmp.join(this.separator)
            return newVal
        },
        handleChangeValue(val){
            // console.log("val=",val)
            const newVal=this.convertListToValue()
            this.currentValue=newVal
            this.updateValue(newVal)
        },

        updateValue(newVal){
            //console.log("sksSelectMultipleByLookupService.updateValue",this.formData,this.propName,newVal)
            this.$emit("input", newVal);
            this.$emit("change",newVal);
            if(!isNullOrUndefined(this.formData)&&!isNullOrUndefined(this.propName)){
                this.formData[this.propName]=newVal
                this.$forceUpdate()
                if(!isNullOrUndefined(newVal)){
                    //已撤销,初始化时绑定会无效,可能渲染完之后 $refs才生效
                    // formRef: Object,
                    this.$emit('clearValidate',this.propName)
                    //绑定的
                    // this.formRef?.clearValidate(this.propName)
                    // setTimeout(()=>{
                    //     this.formRef?.clearValidate(this.propName)
                    // },500)
                }
            }
        },
    },
}
</script>

<style scoped>

</style>


<!--
                                                    :valueRowList="[form.viBajp]"

                <SksSelectMultipleByLookupController option-key="userId" option-label="nickName"
                                                     bean-name="lookupSysUserToList" :formData="form"
                                                     :format-option-label="(item)=>baseFormatOptionLabel({ item: item, optionKey: `proProcedureTaskId`, relationshipNameList: [`workshopName`,`procedureConfName`] })"
                                                     propName="workUserIdStr"></SksSelectMultipleByLookupController>
-->
